package com.wolfman.wolfchat.utils;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.wolfman.wolfchat.po.User;

import java.util.Date;

/**
 * @Title
 * @Description
 * @Author WolfMan
 * @Date 2022/1/15 0:42
 * @Email 2370032534@qq.com
 */
public class JwtUtil {
    /**
     * 过期时间：7天
     */
    public static final int EXPIRE_TIME = 7 * 24 * 60 * 60 * 1000;
    /**
     * 密钥
     */
    private static final String TOKEN_SECRET = "wolf?man8t2so1aj0o*i?o*ds7fa?ia5h3os4fpq";
    /**
     * 签发者
     */
    private static final String ISSUER = "wolfman";

    /**
     * 验证器
     */
    private static final JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET))
            .withIssuer(ISSUER)
            .build();


    /**
     * 生成token（生成失败则抛出异常）
     *
     * @param user
     * @return java.lang.String
     */
    public static String generateJwt(User user) {
        String jwt;
        //当前时间 & 过期时间
        Date now = new Date();
        Date expire = new Date(now.getTime() + EXPIRE_TIME);
        //签发JWT
        jwt = JWT.create()
                //用户ID
                .withSubject(JSON.toJSONString(user))
                //签发者
                .withIssuer(ISSUER)
                //签发时间
                .withIssuedAt(now)
                //过期时间
                .withExpiresAt(expire)
                //加密
                .sign(Algorithm.HMAC256(TOKEN_SECRET));
        return jwt;
    }


    /**
     * 解析jwt
     *
     * @param jwt
     * @return
     */
    public static DecodedJWT verifyJwt(String jwt) {
        //如果发生异常，则说明jwt被篡改了
        try {
            return jwtVerifier.verify(jwt);
        } catch (JWTVerificationException e) {
            return null;
        }
    }

    /**
     * 获取jwt中存储的用户
     *
     * @param decodedjwt
     * @return
     */
    public static User getUser(DecodedJWT decodedjwt) {
        //如果发生异常，则说明jwt被篡改了
        try {
            return JSON.parseObject(decodedjwt.getSubject(), User.class);
        } catch (JWTVerificationException e) {
            return null;
        }
    }

    /**
     * 校验token是否过期
     *
     * @param jwt
     * @return
     */
    public static boolean isExpired(DecodedJWT jwt) {
        if (jwt.getExpiresAt().before(new Date())) {
            return true;
        } else {
            return false;
        }
    }
}
